import axios from 'axios';

import { getToken, setToken } from './token';

const apiUrl = 'http://localhost:3001/';

const http = axios.create({
  baseURL: apiUrl,
  timeout: 1000
});

http.interceptors.request.use(
  (config) => {
    const token = getToken() || '';
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error) => Promise.reject(error)
);

http.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error?.response?.status === 401) {
      const { newToken } = error.response.data;
      setToken(newToken);
    }
    return Promise.reject(error);
  }
);

export { http };
